<template>
  <a-modal
      class="pic-preview"
      :title="title"
      :visible="visible"
      @cancel="handleClose"
      :body-style="bodyStyle"
      width="80%"
  >
    <!-- 图片展示区域 -->
    <div
        class="preview-container"
        @mousemove="handleMove"
        @mouseup="handleStop"
        @mouseleave="handleMouseLeave"
    >
      <img
          :src="currentImage"
          alt=""
          ref="imageRef"
          class="preview-image"
          :style="{
            transform: `rotate(${imageState.rotate}deg) scale(${imageState.scale})`,
            left: `${imageState.position.x}px`,
            top: `${imageState.position.y}px`,
            position: (imageState.position.x !== 0 || imageState.position.y !== 0) ? 'absolute' : 'relative'
          }"
          @mousedown="handleStart"
      />
    </div>

    <!-- 底部操作栏 -->
    <template #footer>
      <div class="footer-container">
        <div v-if="imgList.length > 1" class="thumbnail-container">
          <a-button
              class="nav-button"
              :disabled="currentIndex === 0"
              @click="handlePrev"
          >
            <left-outlined/>
          </a-button>

          <div class="thumbnail-wrapper" ref="thumbnailWrapper">
            <div
                v-for="(img, index) in imgList"
                :key="index"
                class="thumbnail-item"
                :class="{ active: currentIndex === index }"
                @click="handleThumbnailClick(index)"
            >
              <img :src="img" class="thumbnail-image" alt=""/>
            </div>
          </div>

          <a-button
              class="nav-button"
              :disabled="currentIndex === imgList.length - 1"
              @click="handleNext"
          >
            <right-outlined/>
          </a-button>
        </div>

        <div class="toolbar" :class="{ 'single-image': imgList.length === 1 }">
          <a-button @click="handleRotateLeft" title="向左旋转">
            <rotate-left-outlined/>
          </a-button>
          <a-button @click="handleRotateRight" title="向右旋转">
            <rotate-right-outlined/>
          </a-button>
          <a-button @click="handleZoomOut" title="缩小">
            <zoom-out-outlined/>
          </a-button>
          <a-button @click="handleZoomIn" title="放大">
            <zoom-in-outlined/>
          </a-button>
          <a-button @click="handleReset" title="重置">
            <reload-outlined/>
          </a-button>
          <a-button @click="handleDownload" title="下载">
            <download-outlined/>
          </a-button>
        </div>
      </div>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import {ref, reactive, computed, watch, nextTick} from 'vue';
import {
  LeftOutlined,
  RightOutlined,
  RotateLeftOutlined,
  RotateRightOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  DownloadOutlined,
} from '@ant-design/icons-vue';

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: true,
  },
  imgList: {
    type: Array as () => string[],
    required: true,
    validator: (value: string[]) => value.every(item => typeof item === 'string'),
  },
  currentIndex: {
    type: Number,
    required: true,
    default: 0,
  },
  title: {
    type: String,
    default: '图片预览',
  },
});

const emit = defineEmits(['close', 'update:currentIndex', 'download']);

// 图片状态
const imageState = reactive({
  rotate: 0,
  scale: 1,
  position: {
    x: 0,
    y: 0,
  },
});

// 拖拽状态
const dragState = reactive({
  isDragging: false,
  startX: 0,
  startY: 0,
  startPosX: 0,
  startPosY: 0,
});

// Refs
const imageRef = ref<HTMLImageElement | null>(null);
const thumbnailWrapper = ref<HTMLDivElement | null>(null);

// 当前显示的图片
const currentImage = computed(() => props.imgList[props.currentIndex]);

// 模态框内容样式
const bodyStyle = reactive({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  height: '70vh',
  padding: '24px',
  overflow: 'hidden',
});

// 处理关闭
const handleClose = () => {
  resetImageState();
  emit('close');
};

// 重置图片状态
const resetImageState = () => {
  imageState.rotate = 0;
  imageState.scale = 1;
  imageState.position = {x: 0, y: 0};
};

// 旋转图片
const handleRotateLeft = () => {
  imageState.rotate -= 90;
};

const handleRotateRight = () => {
  imageState.rotate += 90;
};

// 缩放图片
const handleZoomIn = () => {
  imageState.scale += 0.1;
};

const handleZoomOut = () => {
  if (imageState.scale > 0.2) {
    imageState.scale -= 0.1;
  }
};

// 重置图片
const handleReset = () => {
  resetImageState();
};

// 下载图片
const handleDownload = () => {
  emit('download', currentImage.value);
};

// 切换图片
const handlePrev = () => {
  if (props.currentIndex > 0) {
    resetImageState();
    emit('update:currentIndex', props.currentIndex - 1);
    scrollThumbnails();
  }
};

const handleNext = () => {
  if (props.currentIndex < props.imgList.length - 1) {
    resetImageState();
    console.log(props.currentIndex);
    emit('update:currentIndex', props.currentIndex + 1);
    scrollThumbnails();
  }
};

// 点击缩略图
const handleThumbnailClick = (index: number) => {
  if (index !== props.currentIndex) {
    resetImageState();
    emit('update:currentIndex', index);
  }
};

// 滚动缩略图
const scrollThumbnails = () => {
  console.log("scrollThumbnails: ", props.currentIndex);
  nextTick(() => {
    if (thumbnailWrapper.value) {
      const thumbnailWidth = 80; // 缩略图宽度 + margin
      const containerWidth = thumbnailWrapper.value.clientWidth;
      const scrollPosition = props.currentIndex * thumbnailWidth - containerWidth / 2 + thumbnailWidth / 2;
      thumbnailWrapper.value.scrollTo({
        left: scrollPosition,
        behavior: 'smooth',
      });
    }
  });
};

// 拖拽相关方法
const handleStart = (e: MouseEvent) => {
  if (e.button === 0) { // 左键点击
    dragState.isDragging = true;
    dragState.startX = e.clientX;
    dragState.startY = e.clientY;
    dragState.startPosX = imageState.position.x;
    dragState.startPosY = imageState.position.y;
  }
};

const handleMove = (e: MouseEvent) => {
  if (dragState.isDragging) {
    const deltaX = e.clientX - dragState.startX;
    const deltaY = e.clientY - dragState.startY;
    imageState.position.x = dragState.startPosX + deltaX;
    imageState.position.y = dragState.startPosY + deltaY;
  }
};

const handleStop = () => {
  dragState.isDragging = false;
};

const handleMouseLeave = () => {
  dragState.isDragging = false;
};

// 监听当前索引变化，自动滚动缩略图
watch(() => props.currentIndex, scrollThumbnails);
</script>

<style lang="less" scoped>
.pic-preview {
  .preview-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    border: 1px solid #f0f0f0;
    background-color: #fafafa;
    position: relative;

    .preview-image {
      max-width: 100%;
      max-height: 100%;
      cursor: move;
      transition: transform 0.3s ease;
    }
  }

  .footer-container {
    display: flex;
    flex-direction: column;
    width: 100%;

    .thumbnail-container {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 8px 0;
      width: 100%;

      .nav-button {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 8px;
      }

      .thumbnail-wrapper {
        display: flex;
        overflow-x: auto;
        scroll-behavior: smooth;
        padding: 4px 0;
        max-width: 600px;
        -webkit-overflow-scrolling: touch;

        &::-webkit-scrollbar {
          height: 4px;
        }

        &::-webkit-scrollbar-thumb {
          background: rgba(0, 0, 0, 0.2);
          border-radius: 2px;
        }

        .thumbnail-item {
          width: 72px;
          height: 72px;
          margin: 0 4px;
          cursor: pointer;
          border: 2px solid transparent;
          transition: border-color 0.3s;
          flex-shrink: 0;

          &.active {
            border-color: aliceblue;
          }

          .thumbnail-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
      }
    }

    .toolbar {
      display: flex;
      justify-content: center;
      padding: 8px 0;
      width: 100%;

      &:not(.single-image) {
        border-top: 1px solid #f0f0f0;
      }
    }
  }
}
</style>